import React, { RefObject, useState } from "react";
import { Form, Input, Button } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import axios from "axios";
function Index() {
  const navigate = useNavigate();
  const [title, settitle] = useState("点击获取验证码");
  const [tel, settel] = useState();

  const onFinish = async (values) => {
    console.log(values);
    const resp = await axios.post("/api/login/tel", values);
    console.log(resp);
    if (resp.data.code == 200) {
      alert("登录成功");
      localStorage.setItem("token", resp.data.data.token);
      localStorage.setItem("userInfo", JSON.stringify(resp.data.data.userInfo));
      navigate("/");
    } else {
      alert("账号或验证码错误");
    }
  };
  const shoujihao = (val) => {
    settel(val);
  };
  const dian = async () => {
    const res = await axios.get("/api/login/code", {
      params: {
        tel,
      },
    });
    console.log(res);
    let miao = 10;

    const tt = setInterval(() => {
      miao--;
      settitle(`${miao}s后获取验证码`);
      if (miao == 0) {
        clearInterval(tt);
        if (res.data.code == 200) {
          settitle(res.data.data);
        }
      }
    }, 1000);
  };
  return (
    <div>
      <Form
        onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Header>水平布局表单</Form.Header>
        <Form.Item
          name="tel"
          label="手机号"
          rules={[
            { required: true, message: "姓名不能为空" },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入正确的手机号",
            },
          ]}
        >
          <Input placeholder="请输入手机号" onChange={shoujihao} />
        </Form.Item>
        <Form.Item
          name="telCode"
          label="短信验证码"
          extra={<a onClick={() => dian()}>{title}</a>}
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
}

export default Index;
